package com.yx.study.leet.questionList.questions;

import org.junit.Test;

/**
 * @Classname LongestPalindrome05
 * @Date 2023/03/13 22:34
 * @Author by yx
 * @Description : 5.最长回文子串
 * https://leetcode.cn/problems/longest-palindromic-substring/
 */
public class LongestPalindrome05 {
    public String longestPalindrome(String s) {
        int length = s.length();
        if (length < 2) {
            return s;
        }
        int maxLen = 1;
        int begin = 0;
        char[] chars = s.toCharArray();

        // 枚举所有长度大于1的子串
        for (int i = 0; i < length - 1; i++) {
            for (int j = i + 1; j < length; j++) {
                if (j - i + 1 > maxLen && vaildPalindromic(chars, i, j)) {
                    maxLen = j - i + 1;
                    begin = i;
                }
            }
        }
        return s.substring(begin, begin + maxLen);
    }

    /**
     * 验证是否是回文子串
     */
    private boolean vaildPalindromic(char[] chars, int left, int right) {
        while (left < right) {
            if (chars[left] != chars[right]) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    @Test
    public void test(){
        longestPalindrome("babad");
    }

}
